package com.fingard.dsp.bank.directbank.gfgs01;

import java.util.Calendar;
import java.util.Date;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.bankInterface.ITransaction;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7515TodayTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7516HisTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.RetAtsTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.detail.RetAtsTransDetail;
import com.fingard.xml.XElement;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

/**
 * Created by F on 2018/11/26.
 * 今日明细，历史明细
 */
public class GFGS01Transaction extends GFGS01Base implements ITransaction{
    /**
     * 历史明细
     * 财务公司:历史交易明细结束日期（由于系统返回报文长度限制，结束日期必须跟开始日期为同一天，也就是只能单日查询）
     * @param p_req7516
     * @return
     * @throws Exception
     */
    @Override
    public RetAtsTrans d_7516_HisTrans(Req7516HisTrans p_req7516) throws Exception{
        RetAtsTrans retAtsTrans = new RetAtsTrans(p_req7516.reqHeader);
        retAtsTrans.writeStart();
        String tmpRespCode = "";
        String tmpRespInfo ="";
        try{
            //起始日期
            Calendar tmpCalendarFrom = Calendar.getInstance();
            tmpCalendarFrom.setTime(p_req7516.getDateFrom());
            //结束日期
            Calendar tmpCalendarTo = Calendar.getInstance();
            tmpCalendarTo.setTime(p_req7516.getDateTo());

            int tmpIntFrom = Integer.parseInt(Format.Date8Format.format(tmpCalendarFrom.getTime()));
            int tmpIntTo = Integer.parseInt(Format.Date8Format.format(tmpCalendarTo.getTime()));
            //东航财务公司明细接口只支持单日查询
            while(tmpIntFrom<=tmpIntTo){
                int intFromStep = tmpIntFrom;//获取起始时间
                tmpCalendarFrom.add(Calendar.DAY_OF_MONTH, 1);//起始时间+1
                tmpIntFrom = Integer.parseInt(Format.Date8Format.format(tmpCalendarFrom.getTime()));//重新设置起始时间
                //拼接报文
                //非公有参数
                XmlTextWriter xmlTextWriter = new XmlTextWriter();
                //拼接请求报文头
                GFGS01Header header=new GFGS01Header();
                header.billType="detailquery";//交易码
                header.roottag="query";
                header.wsdlMethod="queryCurDetail";//提供webservice接口，查询当日交易明细
                writeCommonHeader(xmlTextWriter,header);
                //拼接请求报文体
                xmlTextWriter.writeStartElement("query");
                xmlTextWriter.writeElementString("acc",p_req7516.actNum);//帐号
                //获取今日时间
                Calendar todayFrom = Calendar.getInstance();
                todayFrom.setTime(Format.Date8Format.parse(Format.Date8Format.format(new Date())));
                int todayInt=Integer.parseInt(Format.Date8Format.format(todayFrom.getTime()));
                if(intFromStep<todayInt){//起始时间小于当前时间，查询历史。否则查询今日
                    String date=String.valueOf(intFromStep);
                    xmlTextWriter.writeElementString("begindate", date.substring(0,4)+"-"+date.substring(4,6)+"-"+date.substring(6));//开始时间
                    xmlTextWriter.writeElementString("enddate", date.substring(0,4)+"-"+date.substring(4,6)+"-"+date.substring(6));//结束时间
                    header.wsdlMethod="queryHisDetail";//提供webservice接口，查询历史交易明细
                }
                xmlTextWriter.writeEndElement();
                xmlTextWriter.writeEndDocument();
                //发送请求报文
                String[] resutlt = sendToBank(xmlTextWriter.toXmlString(),header);
                //处理响应报文
                if(resutlt[0].length()==0){
                    StringBuilder tmpSbMsg = new StringBuilder();
                    XmlTextReader tmpBkReader = loadBankRespXmlReader(resutlt[1].trim(),tmpSbMsg);
                    if(tmpBkReader!=null) {
                        String respCode = tmpBkReader.getFirstText("/ufinterface/sendresult/retcode");
                        String respInfo = tmpBkReader.getFirstText("/ufinterface/sendresult/retmemo");
                        if("".equals(respCode) || respCode==null){//查询明细成功，且为空

                        }else if(isActiveRetCode(respCode)) { //查询明细成功，且不为空
                            while (tmpBkReader.read("/ufinterface/sendresult/detail/row")) {
                                XElement readXElement = tmpBkReader.readedXElement;
                                RetAtsTransDetail detail = new RetAtsTransDetail();
                                detail.actArea = p_req7516.actArea;//账户区域
                                detail.actNum = p_req7516.actNum;//银行账号
                                detail.recAccNum = readXElement.getSingleTextNotNull("opacc").trim();//收方银行账号
                                detail.recAccName = readXElement.getSingleTextNotNull("opname").trim();//收方账户名称
                                detail.tranDate = readXElement.getSingleTextNotNull("transdate").trim();//交易日期
                                detail.tranTime = detail.tranDate + " 00:00:00";//交易时间
                                detail.valueDate = detail.tranDate;//起息日，银行没有返回就用tranDate交易日期
                                String payamt = readXElement.getSingleTextNotNull("payamt").trim();//支出金额
                                String getamt = readXElement.getSingleTextNotNull("getamt").trim();//收入金额
                                if (!"".equals(payamt) && payamt!=null) {
                                    if (payamt.indexOf("-") > 0) {
                                        detail.cdFlag = "2";//贷
                                        detail.tranAmt = payamt.substring(1);//交易金额
                                    } else {
                                        detail.cdFlag = "1";//借
                                        detail.tranAmt = payamt;//交易金额
                                    }
                                } else if (!"".equals(getamt) && getamt!=null) {
                                    if (payamt.indexOf("-") > 0) {
                                        detail.cdFlag = "1";//借
                                        detail.tranAmt = getamt.substring(1);//交易金额
                                    } else {
                                        detail.cdFlag = "2";//贷
                                        detail.tranAmt = getamt;//交易金额
                                    }
                                } else {
                                    tmpRespCode = "-1";
                                    tmpRespInfo = "支出金额与收入金额均为空，响应报文异常";
                                    break;
                                }
                                detail.accBal = "";//账户余额
                                String note = readXElement.getSingleTextNotNull("usage").trim();
                                detail.usage = note;//摘要
                                detail.abstr = pickupAbstr(note);//对账码
                                detail.cur = getBankConfig().getMapKeyByValue("curActMapping", p_req7516.actNum);//币种
                                detail.askNumber = readXElement.getSingleTextNotNull("vdef19").trim();
                                detail.originator= readXElement.getSingleTextNotNull("retsourcebusino").trim();
                                retAtsTrans.writeRetDetail(detail);
                            }
                        }else {//查询异常
                            tmpRespCode = "-1";
                            tmpRespInfo = respInfo;
                            break;
                        }
                    }else{
                        tmpRespCode = "-1";
                        tmpRespInfo = tmpSbMsg.toString();
                        break;
                    }
                }else{
                    tmpRespCode = "-1";
                    tmpRespInfo = resutlt[1];
                    break;
                }
            }
        }catch (Exception ex){
            tmpRespCode = "-1";
            tmpRespInfo = ex.getMessage();
            ex.printStackTrace();
            WriteBankLogLn("查询明细异常:"+ex);
        }
        if ("-1".equals(tmpRespCode)) {
            retAtsTrans = new RetAtsTrans(p_req7516.reqHeader);
            retAtsTrans.writeStart();//写返回ATS的统一头部信息
            retAtsTrans.writeRespCode(tmpRespCode);
            retAtsTrans.writeRespInfo(tmpRespInfo);
        }else if(retAtsTrans.getWrittenRdCount() == 0) {
            retAtsTrans.writeRespInfo("交易为空");
            retAtsTrans.writeRespCode("0");
        }
        retAtsTrans.writeEnd();
        return retAtsTrans;
    }

    /**
     * 今日明细
     * @param p_req7515
     * @return
     * @throws Exception
     */
    @Override
    public RetAtsTrans d_7515_TodayTrans(Req7515TodayTrans p_req7515) throws Exception{
        Req7516HisTrans p_req7516 = new Req7516HisTrans(p_req7515.reqHeader);
        p_req7516.actArea = p_req7515.actArea;
        p_req7516.actCur = p_req7515.actCur;
        p_req7516.actNum = p_req7515.actNum;
        String date = Format.Date8Format.format(new Date());
        p_req7516.dateFrom = date;
        p_req7516.dateTo = date;
        return d_7516_HisTrans(p_req7516);
    }
}
